<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="采购单号" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入订单编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="制单人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输制单人"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="采购日期" prop="ddDate">
        <el-date-picker v-model="dateRange"
                        style="display: flex;"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输供应商"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="采购类型" prop="goodsType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择采购类型">
          <el-option
            v-for="dict in dict.type.goods_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="付款状态" prop="payApplyState">
        <el-select v-model="queryParams.payApplyState" placeholder="请选择付款状态">
          <el-option
            v-for="dict in dict.type.buy_pay_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['develop:LvBuyNew:self']" @click="handleAddCg">新增采购单</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddSelf" v-hasPermi="['develop:LvBuy:self']">新增采购单(自采)</el-button>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              :max-height="tableMaxHeight" @sort-change="handleSortChange" show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column sortable label="采购编号" align="center" prop="nos"/>
      <el-table-column sortable label="采购日期" align="center" prop="ddDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ddDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="制单人" align="center" prop="createBy"/>
      <el-table-column sortable align="center" label="来源" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buy_source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column sortable label="供应商名称" align="center" prop="supplierName" show-overflow-tooltip
                       width="120"/>
      <el-table-column label="订单金额" align="center" prop="money"/>
      <el-table-column label="运费" align="center" prop="shippingFee"/>
      <el-table-column sortable align="center" label="采购类别" prop="ywType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.caigou_type" :value="scope.row.ywType"/>
        </template>
      </el-table-column>
      <el-table-column sortable align="center" label="采购类型" prop="goodsType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_type" :value="scope.row.goodsType"/>
        </template>
      </el-table-column>
      <el-table-column sortable label="申请付款金额" align="center" prop="payApplyTotalMoney"/>
      <el-table-column sortable label="实际到货金额" align="center" prop="actualArrivalTotalMoney"/>
      <el-table-column sortable align="center" label="付款状态" prop="payApplyState">
        <template slot-scope="scope">
          <div @click="payApplyList(scope.row)">
            <dict-tag style="cursor: pointer;" :options="dict.type.buy_pay_status" :value="scope.row.payApplyState"/>
          </div>
        </template>
      </el-table-column>

      <el-table-column sortable align="center" label="到货状态" prop="arrivalStatus">
        <template slot-scope="scope">
          <div @click="arriveList(scope.row)">
            <dict-tag style="cursor: pointer;" :options="dict.type.daohuo_status" :value="scope.row.arrivalStatus"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="定金" align="center" prop="dingjin"/>
      <el-table-column sortable label="已付款" align="center" prop="fukuan"/>
      <el-table-column sortable label="剩余欠款" align="center" prop="shengyu"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-money"
                     v-if="scope.row.isDeposit === 'Y' && scope.row.payApplyState === '0' && ((scope.row.dingjin-scope.row.shengyu)>0)"
                     @click="paySupplierBalance(scope.row)" v-hasPermi="['develop:LvBuy:edit']">存入往来
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-money"
                     v-if="scope.row.isDeposit === 'Y' && (scope.row.payApplyState === '0' || scope.row.payApplyState === '-1' ) "
                     @click="payApplyRetainer(scope.row)" v-hasPermi="['develop:LvBuy:edit']">申请付定金
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-ship"
                     v-if="scope.row.depositMerge === '0' && scope.row.isShippingFee === 'Y' && (scope.row.shippingStatus === '0' || scope.row.shippingStatus === '-1' )"
                     @click="payApplyShippingFee(scope.row)" v-hasPermi="['develop:LvBuy:edit']">申请付运费
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-money"
                     v-if="scope.row.payApplyState !== '1' && scope.row.payApplyState !== '-1' && scope.row.payApplyState !== '5' && ((scope.row.isDeposit === 'Y' && scope.row.payApplyState !== '0') || scope.row.isDeposit === 'N')"
                     @click="payApplyUnion(scope.row)" v-hasPermi="['develop:LvBuy:edit']">申请付款
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit"
                     v-if="(scope.row.source ==='0')&&(scope.row.payApplyState === '0' || scope.row.payApplyState === '-1' || scope.row.payApplyState === '-3' ) &&( scope.row.arrivalStatus === '0'  || scope.row.arrivalStatus === '1' )  "
                     @click="handleUpdate(scope.row)" v-hasPermi="['develop:LvBuy:edit']">修改采购单
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit"
                     v-if="(scope.row.source ==='1')&&(scope.row.payApplyState === '0' || scope.row.payApplyState === '-1' || scope.row.payApplyState === '-3' ) &&( scope.row.arrivalStatus === '0'  || scope.row.arrivalStatus === '1' )  "
                     @click="handleUpdateSelf(scope.row)" v-hasPermi="['develop:LvBuy:edit']">修改采购单
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-document"
                     @click="caigou(scope.row)" v-hasPermi="['develop:LvBuy:edit']">采购明细
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-sold-out"
                     v-if="scope.row.arrivalStatus !== '2' "
                     @click="daohuo(scope.row)" v-hasPermi="['develop:LvBuy:edit']">到货处理
          </el-button>
<!--          <el-popconfirm :title="`确认批量到货该采购下所有产品？`" @confirm="handleDaohuoCgd(scope.row)"-->
<!--                         v-if="scope.row.arrivalStatus === '1' "-->
<!--                         style="margin:0 5px;">-->
<!--            <el-button slot="reference" size="mini" type="text" icon="el-icon-finished"-->
<!--                       v-hasPermi="['develop:LvBuy:edit']">全部到货-->
<!--            </el-button>-->
<!--          </el-popconfirm>-->
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDeleteCgd(scope.row)"
                         v-if="(scope.row.payApplyState === '0' || scope.row.payApplyState === '-1' || scope.row.payApplyState === '-3' ) &&( scope.row.arrivalStatus === '0'  || scope.row.arrivalStatus === '1' )  "
                         style="margin:0 5px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                       v-hasPermi="['develop:LvBuy:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <lvBuy-addFormList ref="formCg" @ok="getList"></lvBuy-addFormList>
    <lvBuy-addFormListNew ref="formNew" @ok="getList"></lvBuy-addFormListNew>
    <lvBuy-addFormListSelf ref="formSelf" @ok="getList"></lvBuy-addFormListSelf>
    <caigou-detail-list ref="caigouDetailList" @ok="getList"></caigou-detail-list>
    <daohuo-form ref="daohuoform" @ok="getList"></daohuo-form>
    <tuihuo-form ref="tuihuoform" @ok="getList"></tuihuo-form>
    <fapiao-form ref="fapiaoform" @ok="getList"></fapiao-form>
    <zhifahuo-form ref="zhifahuoform" @ok="getList"></zhifahuo-form>
    <pay-apply-retainer-form ref="payApplyRetainerForm" @ok="getList"></pay-apply-retainer-form>
    <pay-apply-shipping-fee-form ref="payApplyShippingFeeForm" @ok="getList"></pay-apply-shipping-fee-form>
    <pay-apply-union-form ref="payApplyUnionForm" @ok="getList"></pay-apply-union-form>
    <pay-supplier-balance-form ref="supplierBalanceForm" @ok="getList"></pay-supplier-balance-form>
    <lv-daohuo-list-module ref="lvDaohuoListModule" @ok="getList"></lv-daohuo-list-module>
    <pay-apply-list-module ref="payApplyListModule"></pay-apply-list-module>

  </div>
</template>

<script>
import {accSub, deleteAction, getAction, accAdd, downloadFile} from '@/api/manage'
import {list} from "@/api/develop/lvBuy";
import LvBuyAddFormList from '@/views/develop/lvBuy/module/LvBuyAddFormList'
import ZhifahuoForm from '@/views/develop/lvBuy/module/ZhifahuoForm'
import CaigouDetailList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";
import DaohuoForm from "@/views/develop/lvBuy/module/DaohuoForm";
import TuihuoForm from "@/views/develop/lvBuy/module/TuihuoForm";
import FapiaoForm from "@/views/develop/lvBuy/module/FapiaoForm";
import PayApplyRetainerForm from "@/views/develop/payApply/module/PayApplyRetainerForm.vue";
import PaySupplierBalanceForm from "@/views/develop/paySupplierBalance/module/PaySupplierBalanceForm.vue";
import LvBuyAddFormListNew from "@/views/develop/lvBuy/module/LvBuyAddFormListNew.vue";
import LvDaohuoListModule from "@/views/develop/lvDaohuo/module/LvDaohuoListModule.vue";
import PayApplyListModule from "@/views/develop/payApply/module/PayApplyListModule.vue";
import PayApplyUnionForm from "@/views/develop/payApply/module/PayApplyUnionForm.vue";
import PayApplyShippingFeeForm from "@/views/develop/payApply/module/PayApplyShippingFeeForm.vue";
import LvBuyAddFormListSelf from "@/views/develop/lvBuy/module/LvBuyAddFormListSelf.vue";

export default {
  name: "LvBuyList",
  dicts: ["goods_type","buy_source", "caigou_type", "pay_material_status", "daohuo_status", "pay_hardware_status", "fp_state", "buy_pay_status"],
  components: {
    LvBuyAddFormListSelf,
    PayApplyShippingFeeForm,
    PayApplyUnionForm,
    PayApplyListModule,
    LvDaohuoListModule,
    LvBuyAddFormListNew,
    PaySupplierBalanceForm,
    PayApplyRetainerForm,
    LvBuyAddFormList,
    CaigouDetailList,
    DaohuoForm,
    FapiaoForm,
    ZhifahuoForm,
    TuihuoForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      dataList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        mainId: null,
        nos: null,
        ddDate: null,
        subDate: null,
        type: null,
        ywType: null,
        tax: null,
        customerId: null,
        customerName: null,
        isBuy: null,
        money: null,
        dingjin: null,
        shengyu: null,
        shuie: null,
        counts: null,
        dunwei: null,
        supplierId: null,
        supplierName: null,
        deptId: null,
        deptName: null,
        userId: null,
        userName: null,
        state: null,
        createBy: null,
        orderByColumn: 'ddDate',
        isAsc: "descending",
        payApplyState:null
      },
      url: {
        list: '/lvBuy/lvBuy/list',
        removeCg: '/lvBuy/lvBuy/removeCg/',
        export: '/lvBuy/lvBuy/export',
        checkGoodsAllArrived: '/goodsSalebuyall/goodsSalebuyall/checkGoodsAllArrived',
        piliangdaohuo: '/lvBuy/lvBuy/piliangdaohuo/',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "payApplyTotalMoney" || column.property === "actualArrivalTotalMoney" || column.property === "dingjin" || column.property === "fukuan" || column.property === "shengyu") {
          sums[index] = values.reduce((prev, curr) => {

            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    caigou(row) {
      this.$refs.caigouDetailList.showcaigou(row);
    },
    daohuo(row) {
      this.$refs.daohuoform.showdaohuo(row);
    },
    tuihuo(row) {
      this.$refs.tuihuoform.showTuihuo(row);
    },
    fapiao(row) {
      this.$refs.fapiaoform.showfapiao(row);
    },
    dakuan(row) {
      this.$refs.dakuanform.showdakuan(row);
    },
    yunfei(row) {
      this.$refs.yunfeiform.showyunfei(row);
    },
    zhifahuo(row) {
      this.$refs.zhifahuoform.showzhifahuo(row);
    },
    /** 查询采购单列表 */
    getList() {
      this.loading = true;
      /*getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });*/
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    /* handleAdd() {
         this.$refs.form.handleAdd();
     },*/
    handleAddCg() {
      this.$refs.formCg.handleAddCg();
    },

    handleAddSelf(){
      this.$refs.formSelf.handleAdd();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.formNew.handleUpdate(row);
    },


    /** 修改按钮操作 自采 */
    handleUpdateSelf(row) {
      this.$refs.formSelf.handleUpdate(row);
    },

    handleDeleteCgd(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.removeCg, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleDaohuoCgd(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.piliangdaohuo, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("批量到货成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      that.loading = false;
      that.$confirm('是否确认导出采购明细?', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        downloadFile('/lvBuy/lvBuy/export', that.queryParams);
      });
    },

    payApplyRetainer(row) {
      this.$refs.payApplyRetainerForm.show(row);
    },

    payApplyShippingFee(row) {
      this.$refs.payApplyShippingFeeForm.show(row);
    },

    payApplyUnion(row) {
      this.$refs.payApplyUnionForm.show(row);
    },


    // payApplyHardware(row) {
    //   // 付尾款之前  先检查是否订单下所有 产品已经到货
    //   getAction(this.url.checkGoodsAllArrived, { mainId: row.id }).then(response => {
    //     if (response.code === 200) {
    //       if (response.data===0) {
    //         this.$refs.payApplyHardwareForm.show(row);
    //       } else {
    //         this.$modal.msgError("订单下所有产品未全部到货，不能付尾款");
    //       }
    //     } else {
    //       this.$modal.msgError("系统网络问题，请联系管理员!");
    //     }
    //   }).catch(() => {
    //   });
    // },

    paySupplierBalance(row) {
      let money = row.money;
      let dingjin = row.dingjin;
      let balance = accSub(money, dingjin);
      let supplierId = row.supplierId;
      let supplierName = row.supplierName;
      let buyId = row.id;
      this.$refs.supplierBalanceForm.handleAddByBuy(supplierId, supplierName, buyId, balance);
    },

    arriveList(row) {
      this.$refs.lvDaohuoListModule.showByBuy(row.id);
    },

    payApplyList(row) {
      this.$refs.payApplyListModule.showByBuy(row.id);
    },






  }
};
</script>
